package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.exception.base.BaseException;

import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备表Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IoTDAClient iotDAClient;

    /**
     * 查询设备表
     * 
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备表列表
     * 
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备表
     * 
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备表信息
     * 
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }
    /**
     * 同步设备信息
     *
     * */
    @Override
    public void syncDeviceInfo() {
        //设置请求参数
        ListProductsRequest listProduct= new ListProductsRequest();
        //设置限制获取条数
        listProduct.setLimit(50);
        ListProductsResponse response = iotDAClient.listProducts(listProduct);
        if (response.getHttpStatusCode()!=200) {
            throw new  BaseException("获取设备信息失败");
        }
        redisTemplate.opsForValue().set(Constants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));
    }

    /**
     * 获取所有的设备信息
     */
    @Override
    public List<ProductVo> getAllProducts() {
        // 从redis中查询数据
        String jsonStr = (String) redisTemplate.opsForValue().get(Constants.IOT_ALL_PRODUCT_LIST);
        // 如果数据为空，则返回一个空集合
        if(StringUtils.isEmpty(jsonStr)){
            return Collections.emptyList();
        }
        // 解析数据，并返回
        return JSONUtil.toList(jsonStr, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    @Override
    public void register(DeviceDto dto) {
        bindingDeviceOnly(dto);
        bindingForOne(dto);
        Device device;
        //4.注册设备iot
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setDeviceName(dto.getDeviceName());
        body.setProductId(dto.getProductKey());
        body.setNodeId(dto.getNodeId());
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.setSecret(secret);
        body.setAuthInfo(authInfo);
        request.setBody(body);
        AddDeviceResponse response;
        try {
            response=iotDAClient.addDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }
        // 本地保存设备
        // 属性拷贝
        device = BeanUtil.toBean(dto, Device.class);
        // 秘钥
        device.setSecret(secret);
        // 设备id、设备绑定状态
        device.setIotId(response.getDeviceId());
        this.save(device);
    }

    private void bindingDeviceOnly(DeviceDto dto) {
        //1.判断设备名称是否重复
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
        if (device!=null) {
            if (device.getDeviceName() != null) {
                throw new BaseException("设备名称重复");
            }
            //2.判断设备标识是否重复
            if (device.getNodeId() != null) {
                throw new BaseException("设备标识重复");
            }
        }
    }

    private Long bindingForOne(DeviceDto dto) {
        //3.判断同一位置是否绑定了相同的设备
        long count = this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getProductKey, dto.getProductKey())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(dto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, dto.getPhysicalLocationType()));
      return count;
    }

    /**
     * 查询设备的详细数据
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getDeviceDetail(String iotId) {
        //从本地数据库中查询设备数据
        Device device = this.getOne(Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty( device)) {
            throw new BaseException("设备不存在");
        }
        //从iot中查询设备数据
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response=iotDAClient.showDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        //补全数据
        deviceDetailVo.setBindingLocation(Long.valueOf(device.getBindingLocation()));
        deviceDetailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        // 日期转换
        if(StringUtils.isNotEmpty(activeTimeStr)) {
            // 日期时区转换
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            // 日期时区转换
            deviceDetailVo.setActiveTime(DateTimeZoneConverter.utcToShanghai(activeTime));
        }
        return deviceDetailVo;
    }

    /**
     * 删除设备信息
     *
     * @param iotId
     */
    @Override
    public void deleteDeviceByIotId(String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        try {
           iotDAClient.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 删除设备，调用失败");
        }
        Device device = this.getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        this.removeById(device.getId());
    }

    /**
     * 修改设备信息
     *
     * @param deviceDto
     */
    @Override
    public void editDevice(DeviceDto deviceDto) {
        updateIot(deviceDto);
        //判断iot中的设备类型
        Long count = bindingForOne(deviceDto);
        if (count > 0) {
            throw new BaseException("同一位置只能绑定一个设备");
        }
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        this.updateById(device);
    }
    /**
     * 修改iot设备信息
     * @param deviceDto
     * */
    private void updateIot(DeviceDto deviceDto) {
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.setDeviceId(deviceDto.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(deviceDto.getDeviceName());
        request.setBody(body);
        UpdateDeviceResponse response = iotDAClient.updateDevice(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("物联网接口 - 修改设备信息，调用失败");
        }
    }

    /**
     * 查询上传的 数据
     *
     * @param iotId
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        //从iot中查询上传的数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = iotDAClient.showDeviceShadow(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("物联网接口 - 查询设备上传数据，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (ObjectUtil.isEmpty(shadow)) {
            return Collections.emptyList();
        }
        DeviceShadowProperties reported = shadow.get(0).getReported();
        //转化为json处理
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());
        //数据封装
        List<Map<String, Object>> list = new ArrayList<>();
        String eventTimeStr = reported.getEventTime();
        // 把字符串转换为LocalDateTime
        LocalDateTime eventTimeLocalDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        // 时区转换
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);
        jsonObject.forEach((key, value) -> {
            Map<String,Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", eventTime);
            list.add(map);
        });
        return list;
    }

    /**
     * 查询设备的详细数据
     *
     * @param productKey
     */
    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        if (ObjectUtil.isEmpty(productKey)) {
            throw new BaseException("参数错误");
        }
        //1. 查询产品信息
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = iotDAClient.showProduct(request);
        if (response.getHttpStatusCode()!=200) {
            throw new BaseException("物联网接口 - 查询产品信息，调用失败");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (ObjectUtil.isNotEmpty(serviceCapabilities)) {
            return serviceCapabilities;
        }
        return serviceCapabilities;
    }
}
